﻿
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_File_CreateUpdateDirectory_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_File_CreateUpdateDirectory_V2];
GO

CREATE PROCEDURE [dbo].[sproc_File_CreateUpdateDirectory_V2]
    @name               nvarchar(256),
    @ownerId            int,
    @parentDirectoryId  int,
    @directoryId        int output
AS
BEGIN
SET NOCOUNT ON;

IF ( (@directoryId IS NULL) OR (@directoryId <= 0) )
BEGIN
    IF EXISTS (SELECT 1 FROM dbo.UDS_File_Directory WHERE ParentDirectoryId = @parentDirectoryId AND [Name] = @name)
    BEGIN
        RAISERROR(N'指定的目录"%s"已经存在。', 16, 1, @name);
        RETURN -1
    END

    INSERT INTO dbo.UDS_File_Directory (ParentDirectoryId, OwnerId, [Name])
        VALUES( @parentDirectoryId, @ownerId, @name );
    SET @directoryId = @@IDENTITY;
END
ELSE
BEGIN
    IF EXISTS (SELECT 1 FROM dbo.UDS_File_Directory WHERE ParentDirectoryId = @parentDirectoryId AND [Name] = @name AND DirectoryId <> @directoryId)
    BEGIN
        RAISERROR(N'指定的目录"%s"已经存在。', 16, 1, @name);
        RETURN -1
    END

    UPDATE dbo.UDS_File_Directory
        SET
            [Name] = @name,
            LastModified = getdate()
        WHERE DirectoryId = @directoryId;

    IF ( @@ROWCOUNT = 0 )
    BEGIN
        RAISERROR(N'Failed to update the specified directory "%d" since it does not exist.', 16, 1, @directoryId);
    END
END

END
GO

